//
//  MOMarsHelper.m
//  BBVoice
//
//  Created by Hyukooooh on 2024/12/6.
//

#import "MOMarsHelper.h"
#import "NSDate+QAExtension.h"
#import "QAServerBaseInfoModel.h"
#import "MOXLogUntil.h"
#import "QAAPI+Global.h"
#import "QASocketAddressManager.h"

@implementation MOMarsHelper
+ (NSArray *)getAllLogFile{
    NSString* logPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:@"/xlog"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSArray *pathsArr = [fileManager subpathsAtPath:logPath];/*取得文件列表*/
    NSArray *sortedPaths = [pathsArr sortedArrayUsingComparator:^(NSString * firstPath, NSString* secondPath) {
        NSString *firstUrl = [logPath stringByAppendingPathComponent:firstPath];/*获取前一个文件完整路径*/
        NSString *secondUrl = [logPath stringByAppendingPathComponent:secondPath];/*获取后一个文件完整路径*/
        NSDictionary *firstFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:firstUrl error:nil];/*获取前一个文件信息*/
        NSDictionary *secondFileInfo = [[NSFileManager defaultManager] attributesOfItemAtPath:secondUrl error:nil];/*获取后一个文件信息*/
        id firstData = [firstFileInfo objectForKey:NSFileCreationDate];/*获取前一个文件创建时间*/
        id secondData = [secondFileInfo objectForKey:NSFileCreationDate];/*获取后一个文件创建时间*/
         return [secondData compare:firstData];//降序
    }];
     
    NSEnumerator *e = [sortedPaths objectEnumerator];
    NSString *file;
    NSMutableArray *fileData = [NSMutableArray array];
    while((file = [e nextObject]))     //遍历当前目录
    {
        if([[file pathExtension] isEqualToString:@"xlog"])  //取得后缀名为.xlog的文件名
        {
            [fileData addObject:[logPath stringByAppendingPathComponent:file]];//存到数组
        }
    }
    return fileData.copy;
}

+ (void)autoUploadWithArray:(NSArray *)array complete:(void(^)(BOOL success))complete{
    if(array.count <= 0){
        !complete?:complete(YES);
        [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 接口下发的自动上传 上传完毕"];
        return;
    }
    NSMutableArray *allDataArray = [array mutableCopy];
    
    MOAutoReportModel *currentModel = [allDataArray safe_objectAtIndex:0];
    [allDataArray removeObjectAtIndex:0];
    
    [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 接口下发的自动上传 %@---%ld",currentModel.report_date,currentModel.record_id];
    NSArray *logs = [MOMarsHelper getAllLogFile];
    BOOL match = NO;//是否匹配到了，没匹配到要上报传空的
    for (NSString *filePath in logs) {
        NSString *strPickName = [[filePath lastPathComponent] stringByDeletingPathExtension];
        NSString *strDate = [strPickName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%s_",[[@"JiXinLog" md5] UTF8String]] withString:@""];
        NSInteger pickDate = [NSDate mpstringTimeToInt:strDate withFormatter:@"yyyyMMdd"];
        NSString *finalStr = [NSDate timeIntToString:pickDate withFormatter:@"yyyy-MM-dd"];
        if ([finalStr isEqualToString:currentModel.report_date]) {
            if(!kStringIsEmpty(filePath)){
                match = YES;
                [[[QAAPI.new makeSuccessHandler:^(QAResponseModel *response) {
                    [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 接口下发的自动上传 第一步上传成功%@",response.data];
                    if(response.data){
                        [MOMarsHelper saasErrorReportWithFileUrl:response.data date:finalStr recordId:currentModel.record_id complete:^(BOOL success) {
                            if(allDataArray.count > 0){
                                //递归
                                [MOMarsHelper autoUploadWithArray:allDataArray.copy complete:complete];
                            }
                        }];
                    }
                }]makeFailureHandler:^(QAResponseModel *response) {
                    [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 接口下发的自动上传 第一步上传失败%@",NonNullString(response.msg)];
                    if(allDataArray.count > 0){
                        //递归
                        [MOMarsHelper autoUploadWithArray:allDataArray.copy complete:complete];
                    }
                }]uploadFile:filePath fileType:MPUploadFileType_File uploadType:MPUploadType_ErrorLog progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
                    float pro = (bytesSent/totalBytesSent) *100.0;
                    NSLog(@"自动上传日志Tag 错误报告上传进度%f",pro);
                }];
            }
            break;
        }
    }
   
    if(!match){
        [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 接口下发的自动上传 没匹配到%@---%ld",NonNullString(currentModel.report_date),currentModel.record_id];
        [MOMarsHelper saasErrorReportWithFileUrl:@"" date:currentModel.report_date recordId:currentModel.record_id complete:^(BOOL success) {
            if(allDataArray.count > 0){
                //递归
                [MOMarsHelper autoUploadWithArray:allDataArray.copy complete:complete];
            }
        }];
    }
    
}

+ (void)autoUploadTodayLog{
    [MOXLogUntil appenderFlush];
    [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 准备自动上传"];
    NSArray *fileData = [MOMarsHelper getAllLogFile];
    [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 本地日志数量%ld",fileData.count];
    NSString *filePath = [fileData safe_objectAtIndex:0];
    if(!kStringIsEmpty(filePath)){
        NSString *strPickName = [[filePath lastPathComponent] stringByDeletingPathExtension];
        NSString *strDate = [strPickName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%s_",[[@"JiXinLog" md5] UTF8String]] withString:@""];
        NSInteger pickDate = [NSDate mpstringTimeToInt:strDate withFormatter:@"yyyyMMdd"];
        NSString *strPickDate = [NSDate timeIntToString:pickDate withFormatter:@"yyyy-MM-dd"];
        [[[QAAPI.new makeSuccessHandler:^(QAResponseModel *response) {
            [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 第一步上传成功%@",response.data];
            if(response.data){
                [MOMarsHelper saasErrorReportWithFileUrl:response.data date:strPickDate recordId:0 complete:nil];
            }
        }]makeFailureHandler:^(QAResponseModel *response) {
            [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 第一步上传失败%@",NonNullString(response.msg)];
        }]uploadFile:filePath fileType:MPUploadFileType_File uploadType:MPUploadType_ErrorLog progress:^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
            float pro = (bytesSent/totalBytesSent) *100.0;
            NSLog(@"自动上传日志Tag 错误报告上传进度%f",pro);
        }];
    }
}

+ (void)saasErrorReportWithFileUrl:(NSString *)fileUrl date:(NSString *)strPickDate recordId:(NSInteger)recordId complete:(void(^)(BOOL success))complete{
    NSString *serverID = WCICache.serverBaseInfoModel.serverID;
    if(kStringIsEmpty(serverID)){
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:@(2) forKey:@"os"];
    [param setObject:NonNullString(fileUrl) forKey:@"url"];//自动上报，如果url为也要上报，服务端要记录状态
    [param setObject:strPickDate forKey:@"date"];
    [param setObject:NonNullString(WCICache.user.phone) forKey:@"phone"];
    [param setObject:serverID forKey:@"appid"];
    [param setObject:WCICache.user.userAccount forKey:@"account"];
    if(recordId > 0){
        [param setObject:@(recordId) forKey:@"auto_id"];
    }
    [[[QAAPI.new makeSuccessHandler:^(QAResponseModel *response) {
        NSString *result = response.data;
        NSString *decodetestStr = [QATool aes256Decrypt:result];
        NSLog(@"解析saas上传结果%@",decodetestStr);
        QAResponseModel *dModel = [QAResponseModel yy_modelWithJSON:decodetestStr];
        if(dModel.code == 200){
            [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 第二步上传成功%@",fileUrl];
            !complete?:complete(YES);
        }else{
            [MOXLogUntil LogNomalWithString:@"自动上传日志Tag 上传失败%@",NonNullString(response.msg)];
            !complete?:complete(NO);
        }
    }] makeFailureHandler:^(QAResponseModel *response) {
        if (WCICache.hasNet && ![QASocketAddressManager manager].saasHostTryEnd) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [MOMarsHelper saasErrorReportWithFileUrl:fileUrl date:strPickDate recordId:recordId complete:complete];
            });
        }else{
            !complete?:complete(NO);
        }
    }]saasRequestWithUrl:@"/app/error/report" type:MPSaasType_Saas bodyParam:param];
}
@end

@implementation MOAutoReportModel

@end
